<?php
class OrderController extends EController
{
    public $layout = 'main';
    //过滤器
    public function filters()
    {
        return array(
            array(
                'application.filters.BackEndAuthRequestFilter',
            )
        );
    }

    public function actionlist()
    {

        $cookie = new CHttpCookie('aiuserhttpbor', str_replace(Yii::app()->request->baseUrl."/","",$_SERVER["REQUEST_URI"]));
        $cookie->expire = time()+60*60*24*30;
        Yii::app()->request->cookies['aiuserhttpbor']=$cookie;
        $this->layout='list';
        $this->son_menu=0;
        $act_list=ActionMenuHelper::getHiddenMenu();
        $model=new shopOrder('search');
        if(isset($_GET['shopOrder'])){
            $model->attributes=$_GET['shopOrder'];
        }
        $this->render('list',array(
                'dataProvider'=>$model->search(),
                'act_list'=>$act_list,
                'model'=>$model)
        );
    }

    public function actionSend()
    {
        $id = $this->_getId();
        $order = shopOrder::model()->findByPk($id);

        $this->layout='list';
        $this->son_menu=1;
        $model = new OrderSendForm;
        $model->express_company_code = $order->express_company_code;
        $model->express_no = $order->express_no;
        //ajax 验证
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'ajax_form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        if(isset($_POST['OrderSendForm']))
        {
            $model->attributes=$_POST['OrderSendForm'];
            // 验证用户输入，并在判断输入正确后重定向到
            if($model->validate())
            {
                if($model->send($id))
                {
                    Yii::app()->user->setFlash('success',Yii::t('info','operation success'));
                }
                else
                {
                    Yii::app()->user->setFlash('failed',Yii::t('info','operation failed'));
                }
            }
        }
        $this->render('send',array('model'=>$model));
    }

    //获取id
    private function _getId(){
        if(!isset($_GET['id']) || !is_numeric($_GET['id'])){
            throw new CHttpException(400,'Invalid request. id is required!');
        }
        return $_GET['id'];
    }

    public function actionGoodsInfo() {
        $id = $this->_getId();
        $order = shopOrder::model()->findByPk($id);
        $goodsInfo = json_decode($order->goods_info,true);
        $this->render('orderGoodsInfo',array('goodsInfo'=>$goodsInfo));
    }

    public  function actionDownload(){
        $id = $this->_getId();
        $order = shopOrder::model()->findByPk($id);
        $goodsInfo = json_decode($order->goods_info,true);
        $arr = [];
        $i=1;
        $addressInfo = json_decode($order->address_info);
        foreach ($goodsInfo as $r) {
            $arr[] = [
                "no"=>$i,
                "name"=>$order->user->user_name,
                "phone"=>(string)$order->user->user_phone,
                "orderNo"=>$order->order_no,
                "create_time"=>$order->create_time,
                "goodName"=>$r["goodName"],
                "barcode"=>$r["barcode"],
                "num"=>$r["num"],
                "needPoints"=>$r["needPoints"]*$r["num"],
                "receiveName"=>$addressInfo->receiveName,
                "receivePhone"=>(string)$addressInfo->receivePhone,
                "detailAddress"=>$addressInfo->province.$addressInfo->city.$addressInfo->district.$addressInfo->detailDddress,
            ];
            $i++;
        }

       self::excel($arr,$order->order_no);
    }

    public function actionbatchex(){

        if (isset($_POST['id_list']) && $_POST['id_list'] != '') {
            $id_list = explode(",", $_POST['id_list']);
            /*删除ftpHTML页面*/
            if ($id_list) {
                $arr = [];
                foreach ($id_list as $id) {


                    $order = shopOrder::model()->findByPk($id);
                    $goodsInfo = json_decode($order->goods_info,true);

                    $i=1;
                    $addressInfo = json_decode($order->address_info);
                    foreach ($goodsInfo as $r) {
                        $arr[] = [
                            "no"=>$i,
                            "name"=>$order->user->user_name,
                            "phone"=>(string)$order->user->user_phone,
                            "orderNo"=>$order->order_no,
                            "create_time"=>$order->create_time,
                            "goodName"=>$r["goodName"],
                            "barcode"=>$r["barcode"],
                            "num"=>$r["num"],
                            "needPoints"=>$r["needPoints"]*$r["num"],
                            "receiveName"=>$addressInfo->receiveName,
                            "receivePhone"=>(string)$addressInfo->receivePhone,
                            "detailAddress"=>$addressInfo->province.$addressInfo->city.$addressInfo->district.$addressInfo->detailDddress,
                        ];
                        $i++;
                    }



                }
                self::excel($arr,"批量导出");
                $this->showMessage(Yii::t('info', 'operation success'));
            }
        } else {
            $this->showMessage(Yii::t('info', 'select nothing'));
        }
    }


    public static function excel($data,$date) {
        $obj = new PHPExcel();
        // 列标
        $list = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y');

        // 填充第一行数据
        $obj->getActiveSheet()
            ->setCellValue($list[0] . '1', '序号')
            ->setCellValue($list[1] . '1', '用户名')
            ->setCellValue($list[2] . '1', '注册手机号')
            ->setCellValue($list[3] . '1', '订单编号')
            ->setCellValue($list[4] . '1', '订单时间')
            ->setCellValue($list[5] . '1', 'barcode')
            ->setCellValue($list[6] . '1', '商品名称')
            ->setCellValue($list[7] . '1', '数量')
            ->setCellValue($list[8] . '1', '积分')
            ->setCellValue($list[9] . '1', '收件人姓名')
            ->setCellValue($list[10] . '1', '电话')
            ->setCellValue($list[11] . '1', '地址');

        // 填充第n(n>=2, n∈N*)行数据
        $length = count($data);
        for ($i = 0; $i < $length; $i++) {
            $obj->getActiveSheet()->setCellValue($list[0] . ($i + 2), $data[$i]["no"]);
            $obj->getActiveSheet()->setCellValue($list[1] . ($i + 2), $data[$i]["name"]);
            $obj->getActiveSheet()->setCellValue($list[2] . ($i + 2), $data[$i]["phone"],\PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[3] . ($i + 2), $data[$i]["orderNo"]);
            $obj->getActiveSheet()->setCellValue($list[4] . ($i + 2), $data[$i]["create_time"]);;
            $obj->getActiveSheet()->setCellValue($list[5] . ($i + 2), $data[$i]["barcode"]);
            $obj->getActiveSheet()->setCellValue($list[6] . ($i + 2), $data[$i]["goodName"]);
            $obj->getActiveSheet()->setCellValue($list[7] . ($i + 2), $data[$i]["num"]);
            $obj->getActiveSheet()->setCellValue($list[8] . ($i + 2), $data[$i]["needPoints"]);
            $obj->getActiveSheet()->setCellValue($list[9] . ($i + 2), $data[$i]["receiveName"]);
            $obj->getActiveSheet()->setCellValue($list[10] . ($i + 2), $data[$i]["receivePhone"],\PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[11] . ($i + 2), $data[$i]["detailAddress"]);
        }

        // 导出
        ob_clean();
        $write = new PHPExcel_Writer_Excel5($obj);

        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");;
        header('Content-Disposition:attachment;filename="'.$date.'.xls"');
        header("Content-Transfer-Encoding:binary");
        $write->save('php://output');
    }



}